<template>
  <div class="data-sync-page">
    <div class="page-header">
      <h2>数据同步管理</h2>
      <p class="subtitle">批量导入症状和汤药数据</p>
    </div>

    <el-tabs v-model="activeTab" class="sync-tabs">
      <!-- 症状数据同步 -->
      <el-tab-pane label="症状数据同步" name="symptoms">
        <div class="sync-panel">
          <div class="upload-section">
            <div class="upload-tips">
              <h3>Excel 格式要求</h3>
              <ul>
                <li>表头：分类名称 / 症状名称(中文) / 症状名称(英文) / 症状名称(日文) / 症状名称(白俄罗斯)</li>
                <li>分类名称必须在系统中已存在</li>
                <li>症状名称(中文)不能为空</li>
                <li>其他语言为空时将使用中文填充</li>
                <li>重复的症状名称(中文)将被跳过</li>
              </ul>
            </div>

            <el-upload
              ref="symptomUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleSymptomFileChange"
              :limit="1"
              accept=".xlsx,.xls"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将 Excel 文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  仅支持 .xlsx 或 .xls 格式的文件
                </div>
              </template>
            </el-upload>

            <div class="action-buttons" v-if="symptomFile">
              <el-button type="primary" @click="previewSymptomData" :loading="symptomPreviewLoading">
                预览数据
              </el-button>
              <el-button type="success" @click="importSymptomData" :loading="symptomImportLoading" :disabled="!symptomPreviewData.length">
                开始导入
              </el-button>
              <el-button @click="clearSymptomData">清空</el-button>
            </div>
          </div>

          <!-- 预览数据 -->
          <div class="preview-section" v-if="symptomPreviewData.length">
            <h3>数据预览 (共 {{ symptomPreviewData.length }} 条)</h3>
            <el-table :data="symptomPreviewData" border max-height="400" style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="category_name" label="分类名称" width="120" />
              <el-table-column prop="name_zh_cn" label="中文名称" width="150" />
              <el-table-column prop="name_en_us" label="英文名称" width="150" />
              <el-table-column prop="name_ja_jp" label="日文名称" width="150" />
              <el-table-column prop="name_be_by" label="白俄罗斯语" width="150" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'ready' ? 'success' : 'warning'">
                    {{ row.status === 'ready' ? '待导入' : '已存在' }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 导入结果 -->
          <div class="result-section" v-if="symptomImportResult">
            <h3>导入结果</h3>
            <el-alert
              :title="`成功导入 ${symptomImportResult.success} 条，跳过 ${symptomImportResult.skipped} 条，失败 ${symptomImportResult.failed} 条`"
              :type="symptomImportResult.failed > 0 ? 'warning' : 'success'"
              :closable="false"
              show-icon
            />
            <div class="result-details" v-if="symptomImportResult.errors.length">
              <h4>错误详情：</h4>
              <ul>
                <li v-for="(error, index) in symptomImportResult.errors" :key="index">
                  {{ error }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <!-- 汤药数据同步 -->
      <el-tab-pane label="汤药数据同步" name="formulas">
        <div class="sync-panel">
          <div class="upload-section">
            <div class="upload-tips">
              <h3>Excel 格式要求</h3>
              <ul>
                <li>表头：方剂名称(中文) / 方剂名称(英文) / 方剂名称(日文) / 方剂名称(白俄文) / 主症 / 兼症</li>
                <li>方剂名称(中文)不能为空</li>
                <li>其他语言为空时将使用中文填充</li>
                <li>主症/兼症使用分号(;)分隔多个症状</li>
                <li>症状名称必须在系统中已存在</li>
              </ul>
            </div>

            <el-upload
              ref="formulaUploadRef"
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFormulaFileChange"
              :limit="1"
              accept=".xlsx,.xls"
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将 Excel 文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  仅支持 .xlsx 或 .xls 格式的文件
                </div>
              </template>
            </el-upload>

            <div class="action-buttons" v-if="formulaFile">
              <el-button type="primary" @click="previewFormulaData" :loading="formulaPreviewLoading">
                预览数据
              </el-button>
              <el-button type="success" @click="importFormulaData" :loading="formulaImportLoading" :disabled="!formulaPreviewData.length">
                开始导入
              </el-button>
              <el-button @click="clearFormulaData">清空</el-button>
            </div>
          </div>

          <!-- 预览数据 -->
          <div class="preview-section" v-if="formulaPreviewData.length">
            <h3>数据预览 (共 {{ formulaPreviewData.length }} 条)</h3>
            <el-table :data="formulaPreviewData" border max-height="400" style="width: 100%">
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="name_zh_cn" label="中文名称" width="150" />
              <el-table-column prop="name_en_us" label="英文名称" width="150" />
              <el-table-column prop="name_ja_jp" label="日文名称" width="150" />
              <el-table-column prop="name_be_by" label="白俄罗斯语" width="150" />
              <el-table-column prop="main_symptoms" label="主症" width="200" show-overflow-tooltip />
              <el-table-column prop="side_symptoms" label="兼症" width="200" show-overflow-tooltip />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'ready' ? 'success' : row.status === 'warning' ? 'warning' : 'danger'">
                    {{ row.statusText }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 导入结果 -->
          <div class="result-section" v-if="formulaImportResult">
            <h3>导入结果</h3>
            <el-alert
              :title="`成功导入 ${formulaImportResult.success} 条，跳过 ${formulaImportResult.skipped} 条，失败 ${formulaImportResult.failed} 条`"
              :type="formulaImportResult.failed > 0 ? 'warning' : 'success'"
              :closable="false"
              show-icon
            />
            <div class="result-details" v-if="formulaImportResult.errors.length">
              <h4>错误详情：</h4>
              <ul>
                <li v-for="(error, index) in formulaImportResult.errors" :key="index">
                  {{ error }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import { useApi } from '@/composables/useApi'

const { dataSyncApi } = useApi()
const activeTab = ref('symptoms')

// 症状数据相关
const symptomFile = ref(null)
const symptomUploadRef = ref(null)
const symptomPreviewData = ref([])
const symptomPreviewLoading = ref(false)
const symptomImportLoading = ref(false)
const symptomImportResult = ref(null)

// 汤药数据相关
const formulaFile = ref(null)
const formulaUploadRef = ref(null)
const formulaPreviewData = ref([])
const formulaPreviewLoading = ref(false)
const formulaImportLoading = ref(false)
const formulaImportResult = ref(null)

// 处理症状文件选择
const handleSymptomFileChange = (file) => {
  symptomFile.value = file.raw
  symptomPreviewData.value = []
  symptomImportResult.value = null
}

// 处理汤药文件选择
const handleFormulaFileChange = (file) => {
  formulaFile.value = file.raw
  formulaPreviewData.value = []
  formulaImportResult.value = null
}

// 读取 Excel 文件
const readExcelFile = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const firstSheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 })
        resolve(jsonData)
      } catch (error) {
        reject(error)
      }
    }
    reader.onerror = reject
    reader.readAsArrayBuffer(file)
  })
}

// 预览症状数据（纯前端解析，不调用后端API）
const previewSymptomData = async () => {
  if (!symptomFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  symptomPreviewLoading.value = true
  try {
    const excelData = await readExcelFile(symptomFile.value)
    
    if (excelData.length < 2) {
      ElMessage.error('Excel 文件数据为空')
      symptomPreviewLoading.value = false
      return
    }

    // 前端解析数据（跳过表头）
    const parsedData = []
    for (let i = 1; i < excelData.length; i++) {
      const row = excelData[i]
      if (!row[0] || !row[1]) continue // 跳过空行

      const item = {
        category_name: row[0] || '',
        name_zh_cn: row[1] || '',
        name_en_us: row[2] || row[1] || '',
        name_ja_jp: row[3] || row[1] || '',
        name_be_by: row[4] || row[1] || ''
      }
      parsedData.push(item)
    }

    symptomPreviewData.value = parsedData
    ElMessage.success(`成功解析 ${parsedData.length} 条数据，请检查后点击导入`)
  } catch (error) {
    console.error('预览数据失败:', error)
    ElMessage.error('Excel 文件解析失败，请检查文件格式')
  } finally {
    symptomPreviewLoading.value = false
  }
}

// 导入症状数据（调用后端API）
const importSymptomData = async () => {
  if (!symptomPreviewData.value.length) {
    ElMessage.warning('请先预览数据')
    return
  }

  symptomImportLoading.value = true
  try {
    const result = await dataSyncApi.importSymptoms(symptomPreviewData.value)

    if (result.code === 0) {
      symptomImportResult.value = result.data
      ElMessage.success('导入完成')
    } else {
      ElMessage.error(result.msg || '导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    symptomImportLoading.value = false
  }
}

// 清空症状数据
const clearSymptomData = () => {
  symptomFile.value = null
  symptomPreviewData.value = []
  symptomImportResult.value = null
  symptomUploadRef.value?.clearFiles()
}

// 预览汤药数据（纯前端解析，不调用后端API）
const previewFormulaData = async () => {
  if (!formulaFile.value) {
    ElMessage.warning('请先选择文件')
    return
  }

  formulaPreviewLoading.value = true
  try {
    const excelData = await readExcelFile(formulaFile.value)
    
    if (excelData.length < 2) {
      ElMessage.error('Excel 文件数据为空')
      formulaPreviewLoading.value = false
      return
    }

    // 前端解析数据（跳过表头）
    const parsedData = []
    for (let i = 1; i < excelData.length; i++) {
      const row = excelData[i]
      if (!row[0]) continue // 跳过空行

      const item = {
        name_zh_cn: row[0] || '',
        name_en_us: row[1] || row[0] || '',
        name_ja_jp: row[2] || row[0] || '',
        name_be_by: row[3] || row[0] || '',
        main_symptoms: row[4] || '',
        side_symptoms: row[5] || ''
      }
      parsedData.push(item)
    }

    formulaPreviewData.value = parsedData
    ElMessage.success(`成功解析 ${parsedData.length} 条数据，请检查后点击导入`)
  } catch (error) {
    console.error('预览数据失败:', error)
    ElMessage.error('Excel 文件解析失败，请检查文件格式')
  } finally {
    formulaPreviewLoading.value = false
  }
}

// 导入汤药数据（调用后端API）
const importFormulaData = async () => {
  if (!formulaPreviewData.value.length) {
    ElMessage.warning('请先预览数据')
    return
  }

  formulaImportLoading.value = true
  try {
    const result = await dataSyncApi.importFormulas(formulaPreviewData.value)

    if (result.code === 0) {
      formulaImportResult.value = result.data
      ElMessage.success('导入完成')
    } else {
      ElMessage.error(result.msg || '导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    ElMessage.error('导入失败')
  } finally {
    formulaImportLoading.value = false
  }
}

// 清空汤药数据
const clearFormulaData = () => {
  formulaFile.value = null
  formulaPreviewData.value = []
  formulaImportResult.value = null
  formulaUploadRef.value?.clearFiles()
}
</script>

<style scoped>
.data-sync-page {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin: 0;
}

.sync-tabs {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.sync-panel {
  padding: 20px 0;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-tips {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.upload-tips h3 {
  color: #303133;
  font-size: 16px;
  margin: 0 0 12px 0;
  font-weight: 600;
}

.upload-tips ul {
  margin: 0;
  padding-left: 20px;
}

.upload-tips li {
  color: #606266;
  line-height: 1.8;
  font-size: 14px;
}

.upload-demo {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.preview-section,
.result-section {
  margin-top: 30px;
}

.preview-section h3,
.result-section h3 {
  color: #303133;
  font-size: 16px;
  margin-bottom: 16px;
  font-weight: 600;
}

.result-details {
  margin-top: 16px;
  background: #fef0f0;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #f56c6c;
}

.result-details h4 {
  color: #f56c6c;
  font-size: 14px;
  margin: 0 0 8px 0;
  font-weight: 600;
}

.result-details ul {
  margin: 0;
  padding-left: 20px;
}

.result-details li {
  color: #606266;
  line-height: 1.6;
  font-size: 13px;
}

/* Element Plus 样式覆盖 */
:deep(.el-tabs__header) {
  margin-bottom: 20px;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload-dragger) {
  padding: 40px;
}

:deep(.el-table) {
  margin-top: 16px;
}

:deep(.el-alert) {
  margin-bottom: 16px;
}
</style>
